package com.ahu.qifei.fund.task;

import com.ahu.qifei.common.bean.FundHtml;
import com.ahu.qifei.common.bean.FundInfo;
import com.ahu.qifei.common.bean.ResultModel;
import com.ahu.qifei.common.common.enums.ResultEnum;
import com.ahu.qifei.common.entity.Fund;
import com.ahu.qifei.common.service.IFundService;
import com.ahu.qifei.common.service.IMailHTMLTemplateService;
import com.ahu.qifei.common.service.IMailService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ShiQifei
 * @date 2020/11/20 13:52
 */
@Configuration
@EnableScheduling
@Slf4j
public class FundTask {
    @Autowired
    IFundService fundService;
    @Autowired
    IMailHTMLTemplateService mailHTMLTemplateService;

    @Autowired
    @Qualifier("mailServiceImpl")
    IMailService mailService;

    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    // 收件者
    private static final String[] MAIL_RECEIVER = new String[]{"714367321@qq.com"};
    private static final String SUBJECT = "基金监控 ";

    /**
     * 例子：   0 0/30 14-17 ? * MON-FRI
     *          每30分钟  14点-17点  工作日
     */

    // 工作日 14点运行一次
//    @Scheduled(cron="0 0 14 ? * MON-FRI")
    public void  analyseFund() {
        String now = LocalDateTime.now().format(dtf1);
        log.info("执行基金分析，{}", now);
        String startDate = LocalDate.now().plusDays(-31).format(dtf);
        String endDate = LocalDate.now().format(dtf);
        // 查询所有基金
        List<Fund> fundList = fundService.list();
        // 渲染的htmlList
        List<FundHtml> fundHtmlArrayList = new ArrayList<>();
        fundList.forEach(fund -> {
            FundHtml fundHtml = new FundHtml();
            fundHtml.setCode(fund.getCode());
            fundHtml.setName(fund.getName());
            List<Map<String, String>> fundData = new ArrayList<>();
            fundHtml.setData(fundData);
            fundHtmlArrayList.add(fundHtml);
            // 查询详情
            ResultModel result = fundService.detail(fund.getCode(), startDate, endDate);
            if(result.getCode() == ResultEnum.SUCCESS.getCode()) {
                // 基金数据列表
                List<FundInfo> fundInfoList = JSON.parseArray(((JSONArray)result.getData()).toJSONString(), FundInfo.class);
                // 昨天
                FundInfo yesterday = fundInfoList.get(fundInfoList.size() -1);
                // 给每天的数据添加累计增长率
                double startValue = 0;
                for(FundInfo tempFund : fundInfoList) {
                    startValue = Double.valueOf(tempFund.getJZZZL()) + startValue;
                    tempFund.setLeijizzl(Double.valueOf(String.format("%.2f",startValue)));
                }
                // 按照累计增长率从大到小排序
                List<FundInfo> LeijizzlList = fundInfoList.stream()
                        .sorted(Comparator.comparing(a -> Double.valueOf(((FundInfo)a).getLeijizzl())).reversed())
                        .collect(Collectors.toList());
                for(int i = 0 ;i < LeijizzlList.size() ; i++) {
                    if(i == 5) break;
                    FundInfo info = LeijizzlList.get(i);
                    // 相差天数
                    Long betweenDays = LocalDate.parse(yesterday.getFSRQ()).toEpochDay() - LocalDate.parse(info.getFSRQ()).toEpochDay();
                    // 增长率
                    String rate = String.format("%.1f", (yesterday.getLeijizzl() - info.getLeijizzl()));

                    Map<String, String> map = new HashMap(2);
                    map.put("value", rate);
                    map.put("days", betweenDays.toString());
                    fundData.add(map);
                    log.info("{}({})，{}, {}天， 增长率：{}%，",fund.getName() , fund.getCode(), info.getFSRQ(), betweenDays, rate);
                }

            }
        });
        String mailHtml = mailHTMLTemplateService.html(fundHtmlArrayList);
//        System.out.println(mailHtml);
        mailService.sendMimeMessage(MAIL_RECEIVER, SUBJECT + now, mailHtml);
    }
}



